package com.cloudream.glsimple;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * Created by Administrator on 2018/10/12 0012.
 */

public class GL30Triangle extends AppCompatActivity {

    public static final String TAG = GL30Triangle.class.getSimpleName();

    public static final String vertexShaderCode =
            "#version 310 es\n" +
                    "layout(location = 0) in vec4 vPosition;" +
                    "void main() {" +
                    "     gl_Position = vPosition;" +
                    "}";


    public static final String fragmentShaderCode =
            "#version 310 es\n" +
                    " precision mediump float;\n" +
                    " out vec4 fragColor;\n" +
                    " void main() {\n" +
                    "     fragColor = vec4(1.0,0.0,0.0,1.0);\n" +
                    " }";


    public static final float triangleCoords[] = {
            0.5f, 0.5f, 0.0f, // top
            -0.5f, -0.5f, 0.0f, // bottom left
            0.5f, -0.5f, 0.0f  // bottom right
    };


    public static final float color[] = {1.0f, 1.0f, 1.0f, 1.0f}; //白色


    static final int COORDS_PER_VERTEX = 3;

    int mColorHandle;

    //顶点个数
    private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
    //顶点之间的偏移量
    private final int vertexStride = COORDS_PER_VERTEX * 4; // 每个顶点四个字节

    private int mMatrixHandler;

    FloatBuffer vertexBuffer;
    GLSurfaceView glSurfaceView = null;

    // program 句柄
    int mProgram;

    // 着色器Vposition 成员句柄
    int mPositionHandle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        glSurfaceView = new GLSurfaceView(this);
        setContentView(glSurfaceView);


        if(detectOpenGLES30()){
            //设置openGl 版本
            glSurfaceView.setEGLContextClientVersion(3);
            glSurfaceView.setRenderer(new MyTriangleRender());
            // 设置 opengl 刷新模式
            glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        }

    }

    private boolean detectOpenGLES30() {
        ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        ConfigurationInfo info = am.getDeviceConfigurationInfo();

        Log.i(TAG,"reqGlEsVersion = "+info.reqGlEsVersion);
        Log.i(TAG,"needVerion= "+0x30000);

        return (info.reqGlEsVersion >= 0x30000);
    }




    public int loadShader(int type, String shaderCode) {
        //根据type创建顶点着色器或者片元着色器
        int shader = GLES30.glCreateShader(type);
        //将资源加入到着色器中，并编译
        GLES30.glShaderSource(shader, shaderCode);
        GLES30.glCompileShader(shader);

        int[] compiled=new int[1];
        GLES30.glGetShaderiv(shader,GLES30.GL_COMPILE_STATUS,compiled  ,0);
        if(compiled[0] == 0){
            Log.e(TAG,"Could not compile shader:"+type);
            Log.e(TAG,"GLES30 Error:"+ GLES30.glGetShaderInfoLog(shader));
            GLES30.glDeleteShader(shader);
            shader=0;
        }

        return shader;
    }


    private class MyTriangleRender implements GLSurfaceView.Renderer {

        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            GLES30.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
            ByteBuffer bb = ByteBuffer.allocateDirect(triangleCoords.length * 4);
            bb.order(ByteOrder.nativeOrder());

            vertexBuffer = bb.asFloatBuffer();
            vertexBuffer.put(triangleCoords);
            vertexBuffer.position(0);


            int vertexShader = loadShader(GLES30.GL_VERTEX_SHADER,
                    vertexShaderCode);
            int fragmentShader = loadShader(GLES30.GL_FRAGMENT_SHADER,
                    fragmentShaderCode);

            //创建一个空的OpenGLES程序
            mProgram = GLES30.glCreateProgram();
            //将顶点着色器加入到程序
            GLES30.glAttachShader(mProgram, vertexShader);
            //将片元着色器加入到程序中
            GLES30.glAttachShader(mProgram, fragmentShader);
            //连接到着色器程序
            GLES30.glLinkProgram(mProgram);

        }

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            GLES30.glViewport(0, 0, width, height);
        }

        @Override
        public void onDrawFrame(GL10 gl) {

            // 清除屏幕颜色和 深度
            GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT | GLES30.GL_DEPTH_BUFFER_BIT);
            //将程序加入到OpenGLES2.0环境
            GLES30.glUseProgram(mProgram);
            //启用三角形顶点的句柄
            GLES30.glEnableVertexAttribArray(0);

            //准备三角形的坐标数据
            //int indx,
//            int size,
//            int type,
//            boolean normalized,
//            int stride,
//            int offset
            GLES30.glVertexAttribPointer(0, COORDS_PER_VERTEX, GLES30.GL_FLOAT,
                    false, vertexStride, vertexBuffer);
//            //获取片元着色器的vColor成员的句柄
//            mColorHandle = GLES30.glGetUniformLocation(mProgram, "vColor");
//            //设置绘制三角形的颜色
//            GLES30.glUniform4fv(mColorHandle, 1, color, 0);

            GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, vertexCount);
            GLES30.glDisableVertexAttribArray(0);

        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        glSurfaceView.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
        glSurfaceView.onPause();
    }

}
